package com.victor9ac.mashup.es;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.UUID;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentBuilder;

import com.victor9ac.mashup.api.Comment;
import com.victor9ac.mashup.api.Commentaries;
import com.victor9ac.mashup.api.MashupDataType;

import static org.elasticsearch.common.xcontent.XContentFactory.*;

public class ESWriter {

	private ResourceBundle rb;
	protected Client client;

	private final BulkRequestBuilder bulkRequest;

	
	
	public ESWriter(Client client) {
		this.client = client;
		rb = ResourceBundle.getBundle("elasticsearch");

		// initialize
		this.bulkRequest = client.prepareBulk();
	}

	
	public void writeBulk(List<XContentBuilder> contentList,MashupDataType mashupDataType, String indexName) {

		

		try {
			
			for(XContentBuilder content: contentList){
				String bulkRequestId = UUID.randomUUID().toString();
				bulkRequest.add(new IndexRequest(indexName, mashupDataType.name(),bulkRequestId)
                .source(content));
			}
			
			bulkRequest.get();

			
		} catch (ElasticsearchException e) {
			System.out.println("error inserting in bulk");
			e.printStackTrace();
		}

		System.out.println("bulk inserted");

	}



	private void printIndexResponse(IndexResponse response) {

		String esLog = "index: " + response.getIndex() + " | " + "type: "
				+ response.getType() + " | " + "id: " + response.getId()
				+ " | " + "(version:" + response.getVersion() + ")";

		System.out.println(esLog);

	}


	


	

	public void setClient(Client client) {
		this.client = client;
	}

}
